using System;

namespace ErrorDumper.Handlers {
    public class DirectoryExceptionHandler : IExceptionHandler {
        public DirectoryExceptionHandler(string path)
            : this(path, null) { }

        public DirectoryExceptionHandler(string path, IExceptionHandler innerHandler) {
            if ((_path = path) == null)
                throw new ArgumentNullException("path");
            if (!System.IO.Directory.Exists(_path))
                System.IO.Directory.CreateDirectory(_path);
            if (!System.IO.Directory.Exists(_path))
                throw new InvalidOperationException(string.Format(
                    "Could not create directory '{0}'", _path));
            _innerHandler = innerHandler;
        }

        readonly IExceptionHandler _innerHandler;
        readonly string _path;

        public string Path { get { return _path; } }

        public string HandleException(ExceptionPropertyCollection properties, Exception exception) {
            try {
                return "file:" + ExceptionSerializer.Save(properties, exception, _path);
            }
            catch (Exception writeException) {
                if (_innerHandler == null)
                    return null;
                _innerHandler.HandleExceptionSafely(properties, writeException);
                return _innerHandler.HandleExceptionSafely(properties, exception);
            }
        }

        public string HandleException(ExceptionPropertyCollection properties, string content) {
            try {
                return "file:" + ExceptionSerializer.Save(properties, content, _path);
            }
            catch (Exception writeException) {
                if (_innerHandler == null)
                    return null;
                _innerHandler.HandleExceptionSafely(properties, writeException);
                return _innerHandler.HandleExceptionSafely(properties, content);
            }
        }
    }
}